<?php

use App\Models\V1\Managenment\MerchantOperateLogs;
use \Illuminate\Support\Facades\Cache;

/**
 * 统一信息返回
 * @param $data
 * @return \Illuminate\Http\JsonResponse
 */
function ajax_output($code,$message="",$data = [])
{
    if(is_object($data)){
        $data=$data->toArray();
    }
    if(isset($data['data'])){
        return response()->json([
            'status' => $code==200?true:false,
            'code' => $code,
            'message' => $message,
            'data' => [
                'rows'=>$data['data'],
                'currentPage'=>$data['current_page'],
                'total'=>$data['total'],
                'perPage'=>$data['per_page'],
                'lastPage'=>$data['last_page']
            ],
        ],200,[],JSON_UNESCAPED_UNICODE);
    }else{
        return response()->json([
            'status' => $code==200?true:false,
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ],200,[],JSON_UNESCAPED_UNICODE);
    }
}

if( !function_exists("format_date") ){
    /**
     *根据时间戳计算与当前时间的间距及格式化单位
     */
    function format_date($time){
        $t=time()-$time;
        $f=array(
            '31536000'=>'年',
            '2592000'=>'个月',
            '604800'=>'星期',
            '86400'=>'天',
            '3600'=>'小时',
            '60'=>'分钟',
            '1'=>'秒'
        );
        foreach ($f as $k=>$v)    {
            if (0 !=$c=floor($t/(int)$k)) {
                return $c.$v.'前';
            }
        }
    }
}

/**
 * 获取无限分级
 * @param array $items 数据源
 * @param string $pid 父类键值
 * @param string $son 子类键名
 * @return array
 */
function genTree($items, $pid = "pid", $son = "children")
{
    $map = [];
    $tree = [];
    foreach ($items as &$it) {
        $map[$it['id']] = &$it;
    }
    foreach ($items as &$it) {
        $parent = &$map[$it[$pid]];
        if ($parent) {
            $parent[$son][] = &$it;
        } else {
            $tree[] = &$it;
        }
    }
    return $tree;
}

/**
 * 获取多维数组中所有指定键的值，
 * @param array $items 数据源
 * @param string $key 键名
 * @param string $son 子类键名
 * @param array $data
 * @return array
 */
function getsAllValues($items, $key, $son = "children", $data = [])
{
    foreach ($items as $i) {
        $data[] = $i[$key];
        if (array_key_exists($son, $i)) {
            return getsAllvalues($i[$son], $key, $son, $data);
        }
    }
    return $data;
}

/**
 * 生成订单编号，
 * @param array $items 数据源
 */
function order_sn($mch_id=0)
{
    $order_id_main = date('YmdHis') . rand(10000000, 99999999);
    //订单号码主体长度
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for ($i = 0; $i < $order_id_len; $i++) {
        $order_id_sum += (int)(substr($order_id_main, $i, 1));
    }
    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
    $osn = ($mch_id>0?$mch_id:"").$order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
    return $osn;
}

/**
 * 计算签名
 * @param \Illuminate\Http\Request $request
 * @return void
 */
function get_sign($data=[],$key="")
{
    // 移除sign字段
    if (isset($data['sign'])) {
        unset($data['sign']);
    }
    ksort($data);
    $sign = '';
    foreach ($data as $k => $v) {
        if ('sign' !== $k) {
            $sign .= $k . $v;
        }
    }
    return strtoupper(md5(urlencode($sign).$key));
}

/**
 * 将下划线命名转换为驼峰式命名
 * @param $str
 * @param bool $ucfirst
 * @return mixed|string
 */
function convertUnderline($str, $ucfirst = true)
{
    $str = ucwords(str_replace('_', ' ', $str));
    $str = str_replace(' ', '', lcfirst($str));
    return $str;
}

/**
 * 检查通常手机号码
 * @param $mobile
 * @return false|int
 */
function isMobile($mobile) {
    return preg_match("/^1((34[0-8]\d{7})|((3[0-3|5-9])|(4[5-7|9])|(5[0-3|5-9])|(66)|(7[2-3|5-8])|(8[0-9])|(9[1|8|9]))\d{8})$/", $mobile);
}

/**
 * 金额输出通用，可三位间隔
 * @param $amount
 * @param $type 金额格式类型：1：不用三位间隔（100000.00），2：三位间隔（100，000.00）
 * @return string
 */
function amountFormat($amount, $type = 1) {
    return $type === 2 ?
        number_format($amount,2) :
        number_format($amount,2,".","");
}

/**
 * 删除数组中key项并返回值
 * @param $array
 * @param $key
 */
function arrayDeleteKey(&$array, $key) {
    foreach( $array as $k => $v ) {
        if ( $k === $key ) {
            unset($array[$key]);
            return $v;
        }
    }
    return false;
}

/**
 * 二位数组排序
 * @param $array
 * @param $field
 * @param bool $mode
 * @return bool
 */
function arraySort2($array, $field, bool $mode = true) {
    $fields = array_column($array,$field);
    array_multisort($fields,$mode ? SORT_DESC : SORT_ASC, $array);
    return $array;
}

/**
 * 给字符串加上马赛克*，比如名字，手机号，银行卡号等
 * @param string $string
 * @param string $mod 马赛克位置：left,right,both
 * @param int $showLength 最长展示长度
 * @Author GWP
 * @DateTime 2022-01-03
 */
function mosaicString(string $string, $mod = 'left', $showLength = 5)
{
    $length = mb_strlen($string);
    if ( !$length ) return '*';
    if ( $mod == 'both' ) {
        $mLength = 0;
        while( $length / 2 > $mLength ) {
            $jump = intval($mLength/2);
            if ( $mLength % 2 === 0 ) {
                $string[$jump] = '*';
            } else {
                $string[$length-$jump] = '*';
            }
            $mLength ++;
        }
        return $string;
    }

    if ( $mod == 'center' ) {
        $mLength = ceil($length / 3);
        $string = str_split($string);
        for( $i = $mLength; $i < $mLength * 2; $i ++) {
            $string[$i] = '*';
        }
        return implode('',$string);
    }

    $showLength = $length / 2 > $showLength ?
        $showLength : ceil($length / 2);
    if ( $mod == 'left' ) {
        return mb_substr($string, 0, $showLength).
            str_pad('', $length - $showLength, '*');
    } elseif ( $mod == 'right' ) {
        return str_pad('', $length - $showLength, '*')
            . mb_substr($string, -1 * $showLength);
    }
}

/**
 * Returns the url query as associative array
 * @param     string     query
 * @return     array     params
 */
function convertUrlQuery($query="")
{
    $queryParts = explode('&', $query);
    $params = array();
    if(count($queryParts)>0){
        foreach ($queryParts as $param)
        {
            if(strpos($param,"=")===false){
                continue;
            }
            $item = explode('=', $param);

            $params[$item[0]] = $item[1];
        }
    }
    return $params;
}

/**
 *  日期-获取当月最后一天
 *  @return int
 */
function get_lastday($year="",$month="") {
    if($month==2) {
        $lastday=is_leapyear($year)?29 : 28;
    }elseif($month==4||$month==6||$month==9||$month==11){
        $lastday=30;
    }else{
        $lastday = 31;
    }
    return $lastday;
}

/**
 *  日期-是否是闰年
 *  @return int
 */
function is_leapyear($year) {
    return date('L', $year);
}

/**
* 求两个日期之间相差的天数
* (针对1970年1月1日之后，求之前可以采用泰勒公式)
* @param string $day1
* @param string $day2
* @return number
*/
function diffBetweenTwoDays($day1,$day2)
{
    $startdate=strtotime($day1);
    $enddate=strtotime($day2);
    $days=round(($enddate-$startdate)/3600/24) ;
    return $days;
}

/**
 * 获取控制器类名称和方法名称
 * @return array 返回数组
 */
function getControllerAndActionName()
{
    $action = \Route::current()->getActionName();
    list($class, $method) = explode('@', $action);
    $controller = substr(strrchr($class, '\\'), 1);
    return ['controller' => $controller, 'method' => $method];
}

/**
 * 生成随机字符串
 * @param $length
 * @param $type
 * @return string
 */
function random_str($length,$type=1) {
    if($type==1){
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    }else if($type==2){
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    }else if($type==3){
        $chars = '0123456789';
    }
    $str = '';
    for($i = 0; $i < $length; $i++)
    {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

/**
 * curl post
 * @param $url
 * @param $post_data
 * @param $headerArray
 * @param $method
 * @return bool|string
 */
function request_post($url="",$post_data=[],$headerArray=[],$method=""){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data));
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

/**
 * 获取配置
 * @param $key
 * @return mixed|null
 */
function get_setting($key=""){
    if(empty($key)){
        return null;
    }

    $cache=Cache::get('setting_'.$key);
    if(!$cache){
        $setting=\App\Models\V1\Box\Setting::where('name',$key)->first();
        Cache::put('setting_'.$key,$setting->value,600);
        return $setting->value;
    }
    return $cache;
}


function alSendSms($arr)
{
    $host = "https://gyytz.market.alicloudapi.com";
    $path = "/sms/smsSend";
    $method = "POST";
    $appcode = "968d05d8dad947f8bafc75bcdff4f7c5";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    $querys = "mobile={$arr['mobile']}&param=**code**%3A{$arr['code']}%2C**minute**%3A5&smsSignId=2e65b1bb3d054466b82f0c9d125465e2&templateId=908e94ccf08b4476ba6c876d13f084ad";

    $bodys = "";
    $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    if (1 == strpos("$" . $host, "https://")) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    curl_exec($curl);
    return true;

}



